<?php

namespace app\admin\controller\refund;

use app\admin\model\film\Info as FilmInfo;
use app\admin\model\Hall;
use app\admin\model\Order;
use app\admin\model\Schedule as ScheduleModel;
use app\admin\model\user\Coupons as UserCoupons;
use app\common\model\User;
use app\admin\model\user\Level;
use app\common\controller\Backend;
use app\common\model\MoneyLog;
use app\common\model\OrderTicket;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Log;
use think\Queue;
use think\response\Json;
// 加载基础 adapay 基础类
// SDK 初始化文件加载
include_once  dirname(__FILE__). "/../../../../extend/adapay/AdapaySdk/init.php";
// 在文件中设置 DEBUG 为 true 时， 则可以打印日志到指定的日志目录下 LOG_DIR
include_once  dirname(__FILE__). "/../../../../extend/adapay/AdapaySdk/config.php";
/**
 * 退款申请订单
 *
 * @icon fa fa-circle-o
 */
class Refundorder extends Backend
{

    /**
     * Order模型对象
     * @var \app\admin\model\Order
     */
    protected $noNeedLogin = ['test', 'refund'];
    protected $noNeedRight = ['*'];
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Order;
        $this->view->assign("payTypeList", $this->model->getPayTypeList());
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("refundStatusList", $this->model->getRefundStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->with(['hall','film','user','schedule'])
            ->where(['refund_status'=>1])
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        if ($list){
            foreach ($list as $key=>&$value){
                $value['ticket_num'] = OrderTicket::where(['order_id'=>$value['id'],'status'=>1])->count();
            }
        }
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            if ($params['refund_status']==2){
                //审核通过
                if ($row['pay_type']=='wechat'){
                    //微信支付退款 TODO
                    $res = Order::refund($row);
                    $params['refund_result'] = json_encode($res);
                }elseif ($row['pay_type']=='money' || $row['pay_type']=='system'){
                    //余额支付
                    $memo = "订单:".$row['sn']."退款";
                    User::money($row['refund_fee'],$row['user_id'],$memo);
                }elseif ($row['pay_type']=='give_money'){
                    //赠送余额支付
                    $memo = "订单:".$row['sn']."退款";
                    User::giveMoney($row['refund_fee'],$row['user_id'],$memo);
                }
                $params['status'] = 3;
                //票据订单释放座位
                OrderTicket::where(['status'=>1,'order_id'=>$row['id']])->update(['status'=>3]);
                //退回已使用优惠券
                UserCoupons::where(['use_order_id'=>$row['id']])->update(['use_order_id'=>0,'usetime'=>null]);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }


    /*
     * 申请退款
     * */
    public function refund()
    {
        $order_id = $this->request->param('order_id');
        $refund_reason = $this->request->param('refund_reason','');
        if (!$refund_reason){
            $this->error('请选择退款原因');
        }
        $orderModel = new Order();
        $order = $orderModel
            ->where('id', $order_id)
            ->where('status', 1)
            ->find();

        if (empty($order)) {
            $this->error(__('No results were found'));
        }

        $order->status = 3;
        $order->refund_status = 2;
        $order->refund_reason = $refund_reason;
        $order->refund_fee = $order['total_fee'];

//        Log::info($order['user_id']);
        Log::info('订单类型');
        Log::info($order['pay_type']);
        if ($order['pay_type']=='wechat'){
            //微信支付退款 TODO
            $res = Order::refund($order);
            $order['refund_result'] = json_encode($res);
        }elseif ($order['pay_type']=='money' || $order['pay_type']=='system'){
            //余额支付
            $memo = "订单:".$order['sn']."退款";
            User::money($order['refund_fee'],$order['user_id'],$memo);
        }elseif ($order['pay_type']=='give_money'){
            //赠送余额支付
            $memo = "订单:".$order['sn']."退款";
            User::giveMoney($order['refund_fee'],$order['user_id'],$memo);
        }elseif ($order['pay_type']=='adapay_wx_pub'){
            //adapay微信公众号
            #初始化退款对象
            $refund = new \AdaPaySdk\refund();
            $refund_order_no = build_order_no();
            $refund_amt = $order['total_fee'];
            $refund_amt = 0.01;
            $refund_params = array(
                # 原交易支付对象ID
                "payment_id"=> $order['payment_id'],
                # 退款订单号
                "refund_order_no"=> $refund_order_no,
                # 退款金额
                "refund_amt"=> $refund_amt,
                # 退款描述
                "reason"=> "新视界购票退款",
                # 扩展域
                "expend"=> "",
                # 设备静态信息
                "device_info"=> ""
            );
//            halt($refund_params);
            # 发起退款
            $refund->create($refund_params);
            # 对退款结果进行处理
            # $refund->result 类型为数组
            if ($refund->isError()){
                //失败处理
                $this->error($refund->result['error_msg']);
            }
            $order['refund_result'] = json_encode($refund->result);
            $order['refund_no'] = $refund_order_no;
        }


        $order->save();
        OrderTicket::where(['status'=>1,'order_id'=>$order['id']])->update(['status'=>3]);
        UserCoupons::where(['use_order_id'=>$order['id']])->update(['use_order_id'=>0,'usetime'=>null]);


        $this->success('提交成功');
    }
}
